package com.wejoy.video.middle.station.data.service.system.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.wejoy.video.middle.station.data.enums.dict.EnumStatus;
import com.wejoy.video.middle.station.data.mapper.system.ISysDeptMapper;
import com.wejoy.video.middle.station.data.domain.system.SysDept;
import com.wejoy.video.middle.station.data.service.common.IIdWorkerService;
import com.wejoy.video.middle.station.data.service.evs.IEvsHttpService;
import com.wejoy.video.middle.station.data.service.system.ISysDeptService;
import com.wejoy.video.middle.station.data.util.WJAssert;
import com.wejoy.video.middle.station.data.vo.api.DeptNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 系统-部门表
 *
 * @author miracle_j
 * @date 2024年03月27日 16:49:14
 */
@Service
public class SysDeptServiceImpl implements ISysDeptService {
    @Autowired
    private ISysDeptMapper sysDeptMapper;
    @Autowired
    private IIdWorkerService idWorkerService;
    @Autowired
    private IEvsHttpService evsHttpService;

    @Override
    public void save(SysDept req, String operator) {
        req.setOperator(operator);
        if (null == req.getId()) {
            insertSelective(req);
        } else {
            SysDept sysDept = new SysDept();
            sysDept.setId(req.getId());
            if(getCount(sysDept)<1){
                insertSelective(req);
            } else {
                updateSelectiveById(req);
            }
        }
    }

    @Override
    public int insertSelective(SysDept req) {
        if(req.getId()==null){
            req.setId(idWorkerService.getNextId());
        }
        req.setStatus(EnumStatus.NEW.getCode());
        return sysDeptMapper.insertSelective(req);
    }

    @Override
    public int updateSelectiveById(SysDept sysDept) {
        WJAssert.notNull(sysDept, "入参对象不能为空");
        WJAssert.notNull(sysDept.getId(), "id参数错误");
        SysDept where = new SysDept();
        where.setId(sysDept.getId());
        return sysDeptMapper.updateSelective(sysDept, where);
    }

    @Override
    public int getCount(SysDept sysDept) {
        return sysDeptMapper.getCount(sysDept);
    }

    @Override
    public SysDept getOneById(Long id) {
        WJAssert.notNull(id, "id参数错误");
        SysDept where = new SysDept();
        where.setId(id);
        return sysDeptMapper.getOne(where);
    }

    @Override
    public List<SysDept> getList(SysDept sysDept) {
        return sysDeptMapper.getList(sysDept);
    }

    @Override
    public List<SysDept> getPageList(SysDept sysDept) {
        return sysDeptMapper.getPageList(sysDept);
    }

    @Override
    public void audit(Long id, String operator) {
        SysDept req = new SysDept();
        req.setId(id);
        req.setOperator(operator);
        req.setStatus(EnumStatus.AUDIT.getCode());
        updateSelectiveById(req);
    }

    @Override
    public void unaudit(Long id, String operator) {
        SysDept req = new SysDept();
        req.setId(id);
        req.setOperator(operator);
        req.setStatus(EnumStatus.NEW.getCode());
        updateSelectiveById(req);
    }

    @Override
    public void delete(Long id, String operator) {
        SysDept req = new SysDept();
        req.setId(id);
        req.setOperator(operator);
        req.setStatus(EnumStatus.DEL.getCode());
        sysDeptMapper.delete(id);
    }

    @Override
    public List<DeptNode> convertToDesiredFormat(JSONArray jsonArray) {
        List<DeptNode> tree = new ArrayList<>();
        List<DeptNode> nodeList = new ArrayList<>();

        // 遍历jsonArray中的每个节点
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject nodeJson = jsonArray.getJSONObject(i);
            DeptNode node = new DeptNode();
            node.setId(nodeJson.getInteger("id"));
            node.setLabel(nodeJson.getString("name"));
            node.setLeaf(nodeJson.getBoolean("leaf"));
            JSONObject points = evsHttpService.getPoints(evsHttpService.getToken(), 1, 1, node.getId(),null,null);
            if(CollectionUtils.isEmpty(points.getJSONArray("data"))){
                node.setCheckPoint(false);
            }else {
                node.setCheckPoint(true);
            }
            SysDept dept = getOneById(Long.valueOf(node.getId()));
            if(!ObjectUtils.isEmpty(dept)){
                node.setDeptType(dept.getDeptType());
                node.setDescribes(dept.getDescribes());
                node.setUeArea(dept.getUeArea());
                node.setLongitude(dept.getLongitude());
                node.setLatitude(dept.getLatitude());
                node.setSiteArea(dept.getSiteArea());
                node.setModel(dept.getIsModel());
                node.setModelName(dept.getModelName());
                node.setAreaType(dept.getAreaType());
            }
            nodeList.add(node);
        }

        // 将节点连接成树形结构
        for (DeptNode node : nodeList) {
            int parentId = getNodeParentId(jsonArray, node.getId());
            if (parentId == -1) {
                tree.add(node);
            } else {
                DeptNode parent = getNodeById(nodeList, parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(node);
                }
            }
        }

        return tree;
    }

    private DeptNode getNodeById(List<DeptNode> nodeList, int id) {
        for (DeptNode node : nodeList) {
            if (node.getId() == id) {
                return node;
            }
        }
        return null;
    }

    private int getNodeParentId(JSONArray jsonArray, int id) {
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject nodeJson = jsonArray.getJSONObject(i);
            if (nodeJson.getInteger("id") == id) {
                return nodeJson.getInteger("parentId");
            }
        }
        return -1;
    }

    /**
     * 参数校验注解默认使用的方法
     */
    private void checkStringLength(SysDept sysDept, boolean nullAble) {
        WJAssert.notNull(sysDept, "入参对象不能为空");
        WJAssert.limitMaxLength(sysDept.getName(), nullAble, 100, "部门名称不合法!");
        WJAssert.notNull(sysDept.getParentId(),"父级ID不合法!");
        WJAssert.limitMaxLength(sysDept.getDescribes(), true, 500, "描述不合法!");
        WJAssert.limitMaxLength(sysDept.getArea(), true, 50, "所属区域不合法!");
        WJAssert.limitMaxLength(sysDept.getRemark(), true, 255, "备注不合法!");
    }
}
